package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    @Autowired
    private HttpSession session;

    /**
     * 商家注册
     *
     * @param sellerVo
     * @return
     */
    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        seller.setPassword(MD5Coder.md5Encode(seller.getPassword()));
        int i = sellerMapper.insert(seller);
        return i > 0;
    }

    /**
     * 商家登录
     *
     * @param sellerVo
     * @return
     */
    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        //组装条件
        SellerExample example = new SellerExample();
        example.createCriteria()
                .andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));
        //查询list结果集
        List<Seller> list = sellerMapper.selectByExample(example);
        SellerVo resultSellerVo = null;
        //判断结果
        if (!EmptyUtil.isNullOrEmpty(list)) {
            Seller seller = list.get(0);
            //转换VO
            resultSellerVo = BeanConv.toBean(seller, SellerVo.class);
            //放入会话
            session.setAttribute(session.getId(), resultSellerVo);
        }
        return resultSellerVo;
    }

    /**
     * 商家退出
     */
    @Override
    public void loginOutSeller() {
        //从会话中删除当前对象
        session.removeAttribute(session.getId());
    }

    /**
     * 查询商家是否登录
     *
     * @return
     */
    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        Object seller = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(seller);
    }

    /**
     * 根据id查询商家
     *
     * @param sellerVo
     * @return
     */
    @Override
    public SellerVo findSellerVoById(SellerVo sellerVo) {
        Seller seller = sellerMapper.selectByPrimaryKey(sellerVo.getId());
        SellerVo resultSellerVo = BeanConv.toBean(seller, SellerVo.class);
        return resultSellerVo;
    }
}
